package cn.yuyiling.jelly.sr.config;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringReader;
import java.util.Properties;

public class CorsConfigManager {
    private static final Logger logger = LoggerFactory.getLogger(CorsConfigManager.class);
    private Properties properties;
    public CorsConfigManager() {
        try {
            // 构造 URL，连接到 Nacos
            URL url = URL.valueOf("nacos://127.0.0.1:8848");
            // 获取 Nacos 的配置工厂
            DynamicConfigurationFactory factory =
                    ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class)
                            .getExtension("nacos");
            // 获取配置实例
            DynamicConfiguration config = factory.getDynamicConfiguration(url);

            // 从 Nacos 获取配置内容（dataId + group）
            String content = config.getConfig("cors-config.properties", "DEFAULT_GROUP");
            logger.info("Nacos config content: {}", content);
            // 使用 Java Properties 类解析
            properties = new Properties();
            properties.load(new StringReader(content));

        } catch (Exception e) {
            e.printStackTrace();
            properties = new Properties(); // 防止空指针
        }
    }

    public String getAddMapping(){
        return properties.getProperty("cors.addMapping");
    }

    public String getAllowedOrigins(){
        return properties.getProperty("cors.allowedOrigins");
    }

    public String getAllowedHeaders(){
        return properties.getProperty("cors.allowedHeaders");
    }

    public String getExposedHeaders(){
        return properties.getProperty("cors.exposedHeaders");
    }

    public int getMaxAge(){
        return Integer.parseInt(properties.getProperty("cors.maxAge"));
    }
}